<template>
  <el-select v-bind="$attrs">
    <el-option v-for="item in optionList"
               :label="item.label"
               :value="item.value"
               :key="item.value" />
  </el-select>
</template>

<script setup lang="ts">
import {watch} from 'vue'
import { getEnum } from '@/utils/enumUtils'
import { onMounted, ref} from "vue";
import { apiSelectOriginList } from './api'


let optionList = ref([])

const props = defineProps({
  dictionary: String,
  originConfig: {
    type: Object,
    default: {
      baseUrl: null,
      method: null,
      url: null,
    }
  },
  list: Array,
  formatter: {
    type: Function
  },
})

watch(() => props.list, item => {
  if (item && item.length) {
    optionList.value = props.formatter ? props.formatter(item) : item
  }
}, { immediate: true })

const initOptions = async () => {
  const { originConfig, dictionary, formatter } = props
  const {url, baseUrl, method} = originConfig
  if (url) {
    return apiSelectOriginList({
      method: method || 'post',
      url: url,
      baseURL: baseUrl
    }).then(res => {
      if (formatter) {
        optionList.value = formatter(res.data) || []
      } else {
        optionList.value = res.data
      }
    })
  }
  if (dictionary) {
    return getEnum(dictionary, res => {
      optionList.value = formatter ? formatter(res[dictionary]) : res[dictionary]
    })
  }
}

onMounted(() => {
  initOptions()
})

defineExpose({
  optionList
})

</script>

<style lang="scss" scoped>

</style>